package com.monitor.zk.zookeeper.core;

import bean.ZkConfig;
import core.ParamsContext;
import core.annotation.AfterStart;
import core.annotation.BeforeStart;
import core.annotation.StartHandle;
import core.scan.ScanClass;
import core.scan.ScanXmlConfig;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class OnServer implements ApplicationRunner, ApplicationContextAware {

    private ScanXmlConfig scanXmlConfig = ScanXmlConfig.newInScanXmlConfig();
    private ParamsContext paramsContext;
    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.paramsContext = new ParamsContext<>();
        before();
        init();
        after();
    }

    private void init() throws Exception {
        initZookeeper();
    }

    private void initZookeeper() throws Exception {
        log.info("初始化zookeeper");
        ZkConfig zkConfig = (ZkConfig) scanXmlConfig.loadConfig("zk", ZkConfig.class);
        ZkClient zkClient = new ZkClient(zkConfig);
        zkClient.start();
        log.info("初始化zookeeper完成");
    }

    /**
     *
     */
    private void before() throws Exception {
        Map<String, Object> list = applicationContext.getBeansWithAnnotation(BeforeStart.class);
        if(list != null && list.size() > 0){
            for(Object bean : list.values()){
                StartHandle startHandle = (StartHandle) bean;
                startHandle.start(paramsContext);
            }
        }
    }

    private void after() throws Exception {
        Map<String, Object> list = applicationContext.getBeansWithAnnotation(AfterStart.class);
        if(list != null && list.size() > 0){
            for(Object bean : list.values()){
                StartHandle startHandle = (StartHandle) bean;
                startHandle.start(paramsContext);
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
